import WebSocket, { WebSocketServer } from 'ws';
import url from 'url';
import moment from 'moment';

//验证函数
function ClientVerify(info) {
    var result = false;//拒绝
    var params = url.parse(info.req.url, true).query;
    console.log("client verify info :: %j",params);
    if (params["id"] == "kdl" && params["key"] == "76098491") {
        result = true;//通过
    }
    return result;
}

const wss = new WebSocketServer({
    port: 5765,
	verifyClient: ClientVerify,
});
console.log('Listening on http://localhost:5765');

wss.on('connection',
function connection(ws, req) {
    const ip = req.socket.remoteAddress;
    console.log("New Client :: " + ip) 
    ws.on('error', console.error);
    ws.on('message', function message(data, isBinary) {
      let currentTime = moment().format('MMMM Do YYYY, h:mm:ss a');
      console.log(currentTime);
      console.log("Received :: " + data.toString());
      wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
	   client.send(data, { binary: isBinary });
        }
      });
    });
});
